package com.share51.novel.init;

import com.share51.novel.common.utils.ZipUtil;
import com.share51.novel.config.NovelConfig;
import com.share51.novel.entity.Category;
import com.share51.novel.service.CategoryService;
import com.share51.novel.service.TaskService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import java.util.List;

/**
 * 初始化项目配置
 * @author gb
 */
@Slf4j
@Configuration
public class ApplicationInit implements ApplicationRunner {

    @Resource
    private CategoryService categoryService;

    @Resource
    private TaskService taskService;

    @Resource
    private NovelConfig novelConfig;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        ZipUtil.COMMENT=novelConfig.getReliefAffirming();
        this.initCategory();
        this.initBloomFilter();
    }

    /**
     * 初始化分类数据加载到内存中
     */
    private void initCategory(){
        List<Category> categoryList = categoryService.getAllCategory();
        ApplicationCached.initCategory(categoryList);
    }

    /**
     * 初始化布隆过滤器
     */
    private void initBloomFilter(){
        if(!ApplicationCached.SERVER_IS_INIT){
            // 修改业务 crawl 代表每本书，所以做全量过滤，chapter 是章节数据，
            // 每本书只做最新50条增量过滤(因为布隆过滤器没有移除操作，所以定时任务每周重置下次过滤器，防止内存溢出)
            try {
                taskService.initBloomFilter();
            } catch (Exception e) {
                log.error("服务器启动失败，初始化过滤器失败");
                e.printStackTrace();
            }
        }
    }
}
